#!/bin/bash

# 确保脚本在错误时停止
set -e

echo "开始优化部署Todo应用..."

# 配置Docker使用国内镜像源
if [ ! -f /etc/docker/daemon.json ] || ! grep -q "registry-mirrors" /etc/docker/daemon.json; then
    echo "配置Docker使用国内镜像源..."
    mkdir -p /etc/docker
    cat > /etc/docker/daemon.json <<EOF
{
  "registry-mirrors": [
    "https://registry.docker-cn.com",
    "https://hub-mirror.c.163.com",
    "https://mirror.baidubce.com"
  ]
}
EOF
    systemctl daemon-reload
    systemctl restart docker
    echo "Docker已配置为使用国内镜像源"
    # 等待Docker重启完成
    sleep 5
fi

# 生成随机密钥
if grep -q "your_secret_key_here" docker-compose.yml; then
    SECRET_KEY=$(openssl rand -hex 16)
    echo "生成的密钥: $SECRET_KEY"
    sed -i "s/your_secret_key_here/$SECRET_KEY/g" docker-compose.yml
fi

# 构建并启动容器，增加超时时间
echo "构建并启动Docker容器..."
DOCKER_CLIENT_TIMEOUT=120
COMPOSE_HTTP_TIMEOUT=120
export DOCKER_CLIENT_TIMEOUT COMPOSE_HTTP_TIMEOUT
docker-compose up -d --build

echo "部署完成！应用现在应该在http://localhost或您的服务器IP上运行"
